package com.wtpaint.udp.test2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.UUID;

/**
 * UDP提供者，用于提供服务
 * 优先启动
 */
public class UDPProvider {

    public static void main(String[] args) throws IOException {
        String sn = UUID.randomUUID().toString();
        Provider provider = new Provider(sn);
        provider.start();

        System.in.read();
        provider.exit();
    }

    private static class Provider extends Thread {
        private final String sn;

        private boolean done = false;

        private DatagramSocket ds = null;

        public Provider(String sn) {
            super();
            this.sn = sn;
        }

        @Override
        public void run() {
            super.run();

            System.out.println("UDPProvider started.");
            try {

                //作为接收者，制定一个端口用于数据接收
                ds = new DatagramSocket(20000);
                while (!done) {
                    //构建接受实体
                    final byte[] buf = new byte[512];
                    DatagramPacket receivePack = new DatagramPacket(buf, buf.length);

                    ds.receive(receivePack);

                    //打印信息
                    String ip = receivePack.getAddress().getHostAddress();
                    int port = receivePack.getPort();
                    int dataLen = receivePack.getLength();
                    String data = new String(receivePack.getData(), 0, dataLen);
                    System.out.println("UDPProvider receive form ip :" + ip + " port:" + port + " data:" + data);

                    //解析端口号
                    int responsePort = MessageCreator.parsePort(data);
                    if (-1 != responsePort) {
                        //构建回送数据
                        String responseData = MessageCreator.buildWithSN(sn);
                        byte[] responseBytes = responseData.getBytes();
                        //直接根据发送者的信息构建一份回送信息
                        DatagramPacket responsePack = new DatagramPacket(responseBytes,
                                responseBytes.length,
                                receivePack.getAddress(),
                                responsePort);
                        //回送
                        ds.send(responsePack);
                    }

                }
            } catch (Exception ignored) {
            } finally {
                close();
            }
            //完成，关闭
            System.out.println("UDPProvider Complete.");
        }

        private void close() {
            if (null != ds) {
                ds.close();
                ds = null;
            }
        }

        void exit() {
            done = true;
            close();
        }
    }
}
